import os
import logging
import time
from concurrent.futures.thread import ThreadPoolExecutor

from .. import logger
from ..common import wrapper, utils

# from .video import Interface

LOG = logging.getLogger(__name__)


def auto_shopping(android_ip, get_order_delay=2, cycle_delay=5):
    interface = Interface(android_ip)
    while True:
        # 延时几秒，防止云服务器缓存响应不过来
        time.sleep(get_order_delay)
        # 获取此手机的订单任务
        code, result = interface.get_tb_order()
        if code // 100 != 2:
            raise Exception(result)
        code, result = interface.buy_tb_goods(result)
        if code // 100 != 2:
            raise Exception(result)
        while True:
            time.sleep(cycle_delay)
            code, phone_result = interface.get_one_task_status(android_ip)
            if code // 100 != 2:
                raise Exception(phone_result)
            code, result = interface.send_order_status(phone_result)
            if code // 100 != 2:
                raise Exception(result)
            # 如果工作线程结束就退出
            if 'processing' in phone_result and not phone_result['processing']:
                processing, order_number = phone_result['processing'], phone_result['order_number']
                LOG.info('{} thread finish, order_number={}'.format(android_ip, order_number))
                break


class Business:
    def __init__(self, log_name=None):
        self.log_name = log_name or "{}#business.log".format(utils.get_now_day())
        self.check_thread_dead_time = utils.get_os_environ_config_value('CheckThreadDeadTime', int, 30)
        self.init()
        self.android_ip_list = os.getenv("AndroidIpList").split(',')
        self.thread_pool = ThreadPoolExecutor(max_workers=len(self.android_ip_list))
        self.thread_record = None
        self.delay_before_get_order = utils.get_os_environ_config_value('DelayBeforeGetOrder', int, 2)
        self.cycle_report_time = utils.get_os_environ_config_value('DelayInCycleReportStatus', int, 5)

    def start(self):
        self.thread_record = {
            android_ip: self.thread_pool.submit(
                auto_shopping, android_ip, self.delay_before_get_order, self.cycle_report_time)
            for android_ip in self.android_ip_list
        }
        self.check_pool_status()
        # 捕获到键盘中断后推出所有线程池
        self.thread_pool.shutdown()

    def init(self):
        logger.set_logging(self.log_name)

    @wrapper.while_break_when_keyboard_interrupt
    def check_pool_status(self):
        for android_ip, work_thread in self.thread_record.items():
            if not work_thread.done():
                continue
            err_return = wrapper.catch_exception(work_thread.result)()
            LOG.error("{} thread exit, now try to restart it, exit_value='{}'".format(
                android_ip, err_return))
            self.thread_record[android_ip] = self.thread_pool.submit(
                auto_shopping, android_ip, self.delay_before_get_order, self.cycle_report_time)
        time.sleep(self.check_thread_dead_time)
